package cn.jsl.system.service.impl;

import cn.jsl.system.domain.Role;
import cn.jsl.system.mapper.RoleMapper;
import cn.jsl.system.service.IRoleService;
import cn.jsl.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jijie
 * @since 2022-06-11
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    //添加重构
    @Override
    @Transactional //事务回滚
    public void save(Role role){
        super.save(role);
        saveData(role);
    }

    //修改重构
    @Override
    public void update(Role role) {
        //先删除旧权限
        roleMapper.delRoleMenuByRoleId(role.getId());
        roleMapper.delRolePermissionByRoleId(role.getId());
        //再添加新的权限
        saveData(role);
        super.update(role);
    }

    //删除重构
    @Override
    @Transactional
    public void delete(Long id) { //id是角色id
        //删除中间表数据
        roleMapper.delRoleMenuByRoleId(id);
        roleMapper.delRolePermissionByRoleId(id);
        roleMapper.delEmployeeRoleByRoleId(id);
        super.delete(id);
    }

    //批量删除重构
    @Override
    public void patchDelete(List<Long> ids){
        super.patchDelete(ids);
        for (Long id : ids){
            delete(id);
        }
        //有外键关联 - 先删除关联数据 - 在删主表数据
        //super.patchDelete(ids);不需要了 - del(id)中已经删除了
    }

    //抽取公共方法供添加和修改的时候调用
    private void saveData(Role role){
        List<Long> menu = role.getMenu();
        if (menu.size()>0){
            roleMapper.addRoleMenu(role.getId(),menu);
        }
        List<Long> permissions = role.getPermissions();
        if (permissions.size()>0){
            roleMapper.addRolePermissions(role.getId(),permissions);
        }
    }
}
